#include <bits/stdc++.h>
using namespace std;

struct Base {
  void **vtptr;
};
struct Derived {
  void **vtptr;
};
void baseFunc1(Base *This) { printf("base1\n"); }
void baseFunc2(Base *This, int x) { printf("base2 %d\n", x); }
void derivedFunc1(Derived *This) { printf("override\n"); }
void derivedFunc3(Derived *This, double a) { printf("%lf\n", a); }
void c() {
  void **baseVTable = (void **)malloc(2 * sizeof(void *));
  baseVTable[0] = (void *)baseFunc1;
  baseVTable[1] = (void *)baseFunc2;
  void **derivedVTable = (void **)malloc(3 * sizeof(void *));
  derivedVTable[0] = (void *)derivedFunc1;
  derivedVTable[1] = (void *)baseFunc2;
  derivedVTable[2] = (void *)derivedFunc3;

  Base *base = (Base *)malloc(sizeof(Base));
  base->vtptr = baseVTable;
  Derived *drived = (Derived *)malloc(sizeof(Derived));
  drived->vtptr = derivedVTable;
  Base *bases[] = {base, (Base *)drived};

  for (int i = 0; i < 2; i++) {
    (((void (**)(Base *))bases[i]->vtptr)[0])(bases[i]);
    (((void (**)(Base *, int))bases[i]->vtptr)[1])(bases[i], i);
  }
  // 可无损转回 Derived* 调用函数3
  (((void (**)(Base *, double))bases[1]->vtptr)[2])(bases[2], 0.1);
}

void cpp() {
  class Base {
   public:
    virtual void func1() { printf("base1\n"); }
    virtual void func2(int x) { printf("base2\n"); }
  };
  class Derived : public Base {
   public:
    void func1() override { printf("override\n"); }
    virtual void func3(double a) { printf("%lf\n", a); }
  };
  Base *base = new Base();
  Derived *derived = new Derived();
  Base *bases[] = {base, derived};
  for (int i = 0; i < 2; i++) {
    bases[i]->func1();
    bases[i]->func2(i);
  }
  // 可无损转回 Derived* 调用函数3
  ((Derived*)bases[1])->func3(0.1);
}

int main() {
  c();
  cout << "--------" << endl;
  cpp();
}
